package com.xuanfu_button;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;


import net.xxhong.rosclient.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/8/15/015.
 */

public class NameListDialog extends Dialog implements AdapterView.OnItemClickListener {

    private ListView mLv;
    private List<String> nameList;
    private NameAdapter mAdapter;
    private Context mContext;
    private OnDialogItemClickListener mListener;

    public NameListDialog(@NonNull Context context) {
        super(context, R.style.My_Dialog);
        mContext = context;
        nameList = new ArrayList<>();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_name_list);
        initView();
        initData();
        initListener();
    }

    public void putData(@NonNull List<String> data) {
        nameList.clear();
        nameList.addAll(data);
        mAdapter.notifyDataSetChanged();
    }

    private void initListener() {
        mLv.setOnItemClickListener(this);
    }

    private void initData() {
        mAdapter = new NameAdapter();
        mLv.setAdapter(mAdapter);
    }

    private void initView() {
        mLv = (ListView) findViewById(R.id.lv);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (mListener != null) {
            mListener.onDialogItemClick(nameList.get(i));
            dismiss();
        }
    }

    public interface OnDialogItemClickListener {
        void onDialogItemClick(String name);
    }

    public void setOnDialogItemClickListener(OnDialogItemClickListener listener) {
        mListener = listener;
    }

    class NameAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return nameList.size();
        }

        @Override
        public Object getItem(int i) {
            return nameList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = View.inflate(mContext, R.layout.item_name, null);
                holder.tv = (TextView) view.findViewById(R.id.tv);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            holder.tv.setText(nameList.get(i));
            return view;
        }

        class Holder {
            TextView tv;
        }
    }
}
